package cn.com.analyze;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import org.jnetpcap.Pcap;
import org.jnetpcap.packet.JPacket;
import org.jnetpcap.packet.JPacketHandler;

import android.util.Log;

public class Parser {
	private List<JPacket> packets;
	private Pcap pcap;
	
	TotalBytes tb;
	
	public static String hostip;
	
	public Parser()
	{
		packets = new ArrayList<JPacket>();
		hostip = getLocalIP();
		tb = new TotalBytes();
	}
	
	public void readPackets(String file)
	{
		StringBuilder builder = new StringBuilder();
		pcap = Pcap.openOffline(file, builder);
		
		JPacketHandler<Object> handler = new JPacketHandler<Object>(){

			@Override
			public void nextPacket(JPacket packet, Object user) {
				// TODO Auto-generated method stub
				//packets.add(packet);
				tb.add(packet);
			}
			
		};
		
		pcap.loop(-1, handler, null);
		pcap.close();
		
		//startParser();
	}
	
	int totalBytes;
	
	
	public int getTotalBytes()
	{
		totalBytes = tb.getTotalBytes();
		return totalBytes;
	}
	
	private String getLocalIP()
	{
		try {
			for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
			en.hasMoreElements(); )
			{
				NetworkInterface ni = en.nextElement();
				for(Enumeration<InetAddress> ipAddr = ni.getInetAddresses();
				ipAddr.hasMoreElements(); )
				{
					InetAddress ia = ipAddr.nextElement();
					if(!ia.isLoopbackAddress())
					{
						Log.i("Parser.getLocalIP", ia.getHostAddress().toString());
						return ia.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
